package com.example.demo.common.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//用于校验用户身份
@Slf4j
public class JwtUtil {
    private static final String secret = "";
    private static final Key key = Keys.hmacShaKeyFor((Decoders.BASE64.decode(secret)));

    private static final long expiration = 24 * 60 * 60 * 1000;
    //1.生成token
    public static String genToken(Map<String, Object> map){
        return Jwts.builder()
                .setClaims(map)
//                .setSubject() //载荷信息也可以放置到这里
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .setIssuedAt(new Date())
                .signWith(key)
                .compact();
    }

    //2.校验token


    //0.测试生成token

    public static Claims parseToken(String token) {

        if(!StringUtils.hasLength(token)){
            return null;
        }
        //jw解析器
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
            body = build.parseClaimsJws((token)).getBody();
            return body;
        } catch (ExpiredJwtException e) {
            log.error("token过期, token:{}", token);
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            log.error("签名不匹配,token:{}", token);
        } catch (Exception e) {
            log.error("token解析失败,token:{}", token);
        }
        return null;
    }


}
